<template>
    <div>
        <basic-container>
            <div class="app-container">
                <!-- 左右分屏布局 -->
                <div class="dual-station-layout">
                    <!-- 左侧 - 工站1 -->
                    <div class="station-panel station-1">
                        <div class="station-header">
                            <h3>工站1 SOP管理</h3>
                        </div>
                        
                        <!-- 工站1查询表单 -->
                        <el-form :model="station1Query" ref="station1QueryForm" size="small" :inline="true">
                            <el-form-item label="设备名称">
                                <el-select style="width: 160px;" v-model="station1Query.facility_id" placeholder="请选择" clearable @change="saveStation1Cache">
                                    <el-option v-for="item in menuList" :key="item.facility_id" :label="item.name"
                                        :value="item.facility_id">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                           
                            <el-form-item label="查询方式">
                                <el-select style="width: 160px;" v-model="station1Query.query_type" placeholder="请选择">
                                    <el-option label="根据当前生产机种查询SOP" :value="1"></el-option>
                                    <el-option label="根据选择机种查询sop" :value="0"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="机种名称">
                                <el-select style="width: 160px;" v-model="station1Query.aircraft_id" placeholder="请选择" clearable @change="saveStation1Cache">
                                    <el-option v-for="item in roleOptions" :key="item.aircraft_id" :label="item.aircraft"
                                        :value="item.aircraft_id">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item>
                                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleStation1Query">搜索</el-button>
                                <el-button icon="el-icon-refresh" size="mini" @click="resetStation1Query">重置</el-button>
                            </el-form-item>
                        </el-form>

                        <!-- 工站1 PDF显示 -->
                        <div v-if="station1Data.length > 0" v-loading="station1Loading" class="station-content">
                            <el-card v-for="(item, index) in station1Data" :key="'station1-' + index" class="pdf-card" shadow="hover">
                                <div slot="header" class="pdf-card-header">
                                    <span class="pdf-title">{{ item.facility_name || '工站1 SOP' }}</span>
                                </div>
                                <div class="pdf-content">
                                    <div v-if="item.pdfSrc && !item.loading" class="pdf-viewer">
                                        <canvas :ref="`station1Canvas${index}`" class="pdf-canvas" @click="openStation1Fullscreen(item, index)"></canvas>
                                        <div class="pdf-controls">
                                            <el-button size="small" @click="prevStation1Page(item)" :disabled="item.currentPage <= 1">上一页</el-button>
                                            <span class="page-info">{{ item.currentPage || 1 }} / {{ item.totalPages || 1 }}</span>
                                            <el-button size="small" @click="nextStation1Page(item)" :disabled="item.currentPage >= item.totalPages">下一页</el-button>
                                            <el-button size="small" type="primary" @click="openStation1Fullscreen(item, index)">全屏查看</el-button>
                                        </div>
                                    </div>
                                    <div v-else-if="item.loading" class="pdf-loading">
                                        <i class="el-icon-loading"></i>
                                        <span>正在加载工站1 PDF...</span>
                                    </div>
                                    <div v-else class="pdf-error">
                                        <i class="el-icon-document-delete"></i>
                                        <span>暂无工站1 PDF文件</span>
                                    </div>
                                </div>
                            </el-card>
                        </div>
                        <div v-else-if="!station1Loading" class="empty-state">
                            <el-empty description="暂无工站1数据"></el-empty>
                        </div>
                    </div>

                    <!-- 右侧 - 工站2 -->
                    <div class="station-panel station-2">
                        <div class="station-header">
                            <h3>工站2 SOP管理</h3>
                        </div>
                        
                        <!-- 工站2查询表单 -->
                        <el-form :model="station2Query" ref="station2QueryForm" size="small" :inline="true">

                            <el-form-item label="设备名称">
                                <el-select style="width: 160px;" v-model="station2Query.facility_id" placeholder="请选择" clearable @change="saveStation2Cache">
                                    <el-option v-for="item in menuList" :key="item.facility_id" :label="item.name"
                                        :value="item.facility_id">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                     
                            <el-form-item label="查询方式">
                                <el-select style="width: 160px;" v-model="station2Query.query_type" placeholder="请选择">
                                    <el-option label="根据当前生产机种查询SOP" :value="1"></el-option>
                                   <el-option label="根据选择机种查询sop" :value="0"></el-option>
                                </el-select>
                            </el-form-item>
                           
                            <el-form-item label="机种名称">
                                <el-select style="width: 160px;" v-model="station2Query.aircraft_id" placeholder="请选择" clearable @change="saveStation2Cache">
                                    <el-option v-for="item in roleOptions" :key="item.aircraft_id" :label="item.aircraft"
                                        :value="item.aircraft_id">
                                    </el-option>
                                </el-select>
                            </el-form-item>

                            <el-form-item>
                                <el-button type="success" icon="el-icon-search" size="mini" @click="handleStation2Query">搜索</el-button>
                                <el-button icon="el-icon-refresh" size="mini" @click="resetStation2Query">重置</el-button>
                            </el-form-item>
                        </el-form>

                        <!-- 工站2 PDF显示 -->
                        <div v-if="station2Data.length > 0" v-loading="station2Loading" class="station-content">
                            <el-card v-for="(item, index) in station2Data" :key="'station2-' + index" class="pdf-card" shadow="hover">
                                <div slot="header" class="pdf-card-header">
                                    <span class="pdf-title">{{ item.facility_name || '工站2 SOP' }}</span>
                                </div>
                                <div class="pdf-content">
                                    <div v-if="item.pdfSrc && !item.loading" class="pdf-viewer">
                                        <canvas :ref="`station2Canvas${index}`" class="pdf-canvas" @click="openStation2Fullscreen(item, index)"></canvas>
                                        <div class="pdf-controls">
                                            <el-button size="small" @click="prevStation2Page(item)" :disabled="item.currentPage <= 1">上一页</el-button>
                                            <span class="page-info">{{ item.currentPage || 1 }} / {{ item.totalPages || 1 }}</span>
                                            <el-button size="small" @click="nextStation2Page(item)" :disabled="item.currentPage >= item.totalPages">下一页</el-button>
                                            <el-button size="small" type="success" @click="openStation2Fullscreen(item, index)">全屏查看</el-button>
                                        </div>
                                    </div>
                                    <div v-else-if="item.loading" class="pdf-loading">
                                        <i class="el-icon-loading"></i>
                                        <span>正在加载工站2 PDF...</span>
                                    </div>
                                    <div v-else class="pdf-error">
                                        <i class="el-icon-document-delete"></i>
                                        <span>暂无工站2 PDF文件</span>
                                    </div>
                                </div>
                            </el-card>
                        </div>
                        <div v-else-if="!station2Loading" class="empty-state">
                            <el-empty description="暂无工站2数据"></el-empty>
                        </div>
                    </div>
                </div>
            </div>
        </basic-container>

        <!-- 工站1全屏PDF查看 -->
        <div v-if="station1FullscreenVisible" class="fullscreen-pdf-container" @click="closeStation1Fullscreen">
            <div class="fullscreen-content" @click.stop>
                <canvas ref="station1FullscreenCanvas" class="fullscreen-pdf-canvas"></canvas>
                <div class="fullscreen-controls">
                    <el-button @click="prevStation1FullscreenPage" :disabled="station1FullscreenCurrentPage <= 1">上一页</el-button>
                    <span class="page-info">{{ station1FullscreenCurrentPage }} / {{ station1FullscreenTotalPages }}</span>
                    <el-button @click="nextStation1FullscreenPage" :disabled="station1FullscreenCurrentPage >= station1FullscreenTotalPages">下一页</el-button>
                    <el-button @click="station1FullscreenZoomOut" :disabled="station1FullscreenScale <= 0.5">缩小</el-button>
                    <span class="zoom-info">{{ Math.round(station1FullscreenScale * 100) }}%</span>
                    <el-button @click="station1FullscreenZoomIn" :disabled="station1FullscreenScale >= 3">放大</el-button>
                    <el-button type="danger" @click="closeStation1Fullscreen">关闭</el-button>
                </div>
            </div>
        </div>

        <!-- 工站2全屏PDF查看 -->
        <div v-if="station2FullscreenVisible" class="fullscreen-pdf-container" @click="closeStation2Fullscreen">
            <div class="fullscreen-content" @click.stop>
                <canvas ref="station2FullscreenCanvas" class="fullscreen-pdf-canvas"></canvas>
                <div class="fullscreen-controls">
                    <el-button @click="prevStation2FullscreenPage" :disabled="station2FullscreenCurrentPage <= 1">上一页</el-button>
                    <span class="page-info">{{ station2FullscreenCurrentPage }} / {{ station2FullscreenTotalPages }}</span>
                    <el-button @click="nextStation2FullscreenPage" :disabled="station2FullscreenCurrentPage >= station2FullscreenTotalPages">下一页</el-button>
                    <el-button @click="station2FullscreenZoomOut" :disabled="station2FullscreenScale <= 0.5">缩小</el-button>
                    <span class="zoom-info">{{ Math.round(station2FullscreenScale * 100) }}%</span>
                    <el-button @click="station2FullscreenZoomIn" :disabled="station2FullscreenScale >= 3">放大</el-button>
                    <el-button type="danger" @click="closeStation2Fullscreen">关闭</el-button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
// 导入PDF.js库
const pdfjsLib = require('pdfjs-dist');
pdfjsLib.GlobalWorkerOptions.workerSrc = require('pdfjs-dist/build/pdf.worker.entry');

const loadPDFJS = () => {
    return Promise.resolve(pdfjsLib);
};

import {
    getkindList,
    getStation,
    getdkind,
} from "@/api/arftsop";

export default {
    data() {
        return {
            tableTile: ['机种名称', '双工站SOP'],
            checked: false,
            roleOptions: [],
            menuList: [],
            
            // 双工站左右分屏查询参数
            station1Query: {
                aircraft_id: null,
                facility_id: null,
                query_type: 1,
                index: 1,
                size: 10,
            },
            station2Query: {
                aircraft_id: null,
                facility_id: null,
                query_type: 1,
                index: 1,
                size: 10,
            },
            
            // 双工站数据
            station1Data: [],
            station1Loading: false,
            station2Data: [],
            station2Loading: false,
            
            // 全屏PDF查看相关
            station1FullscreenVisible: false,
            station1FullscreenPdfDoc: null,
            station1FullscreenCurrentPage: 1,
            station1FullscreenTotalPages: 1,
            station1FullscreenScale: 1,
            
            station2FullscreenVisible: false,
            station2FullscreenPdfDoc: null,
            station2FullscreenCurrentPage: 1,
            station2FullscreenTotalPages: 1,
            station2FullscreenScale: 1,
            
            // 基础参数
            queryParams: {
                index: 1,
                size: 1000,
            },
        };
    },

    async mounted() {
        // 初始化PDF.js
        await loadPDFJS();
        console.log('PDF.js已成功加载');

        // 从本地缓存加载选择项
        this.loadStation1Cache();
        this.loadStation2Cache();

        console.log('开始加载基础数据...');
        this.getList();
        this.getdkindList();
        console.log('基础数据加载方法已调用');

        // 添加键盘事件监听
        document.addEventListener('keydown', this.handleKeyDown);
    },

    methods: {
        getList() {
            console.log('正在调用 getkindList API，参数:', this.queryParams);
            getkindList(this.queryParams).then((response) => {
                console.log('getkindList API 响应:', response);
                this.menuList = response.data.data;
                console.log(this.menuList, "双工站设备列表");
            }).catch(error => {
                console.error('获取设备列表失败:', error);
                this.$message.error('获取设备列表失败');
            });
        },

        getdkindList() {
            console.log('正在调用 getdkind API');
            getdkind().then((res) => {
                console.log('getdkind API 响应:', res);
                this.roleOptions = res.data.data;
                console.log(this.roleOptions, '机种列表');
            }).catch(error => {
                console.error('获取机种列表失败:', error);
                this.$message.error('获取机种列表失败');
            });
        },

        // 工站1缓存方法
        loadStation1Cache() {
            const cachedData = localStorage.getItem('rdearftsopdou_station1_cache');
            if (cachedData) {
                try {
                    const cache = JSON.parse(cachedData);
                    if (cache.aircraft_id) {
                        this.station1Query.aircraft_id = cache.aircraft_id;
                    }
                    if (cache.facility_id) {
                        this.station1Query.facility_id = cache.facility_id;
                    }
                    console.log('从缓存加载工站1选择项:', cache);
                } catch (error) {
                    console.error('工站1缓存数据解析失败:', error);
                }
            }
        },

        saveStation1Cache() {
            const cacheData = {
                aircraft_id: this.station1Query.aircraft_id,
                facility_id: this.station1Query.facility_id,
                timestamp: Date.now()
            };
            localStorage.setItem('rdearftsopdou_station1_cache', JSON.stringify(cacheData));
            console.log('保存工站1选择项到缓存:', cacheData);
        },

        // 工站2缓存方法
        loadStation2Cache() {
            const cachedData = localStorage.getItem('rdearftsopdou_station2_cache');
            if (cachedData) {
                try {
                    const cache = JSON.parse(cachedData);
                    if (cache.aircraft_id) {
                        this.station2Query.aircraft_id = cache.aircraft_id;
                    }
                    if (cache.facility_id) {
                        this.station2Query.facility_id = cache.facility_id;
                    }
                    console.log('从缓存加载工站2选择项:', cache);
                } catch (error) {
                    console.error('工站2缓存数据解析失败:', error);
                }
            }
        },

        saveStation2Cache() {
            const cacheData = {
                aircraft_id: this.station2Query.aircraft_id,
                facility_id: this.station2Query.facility_id,
                timestamp: Date.now()
            };
            localStorage.setItem('rdearftsopdou_station2_cache', JSON.stringify(cacheData));
            console.log('保存工站2选择项到缓存:', cacheData);
        },

        // 工站1查询方法
        handleStation1Query() {
            this.station1Query.index = 1;
            this.loadStation1PDF();
        },

        resetStation1Query() {
            this.station1Query = {
                aircraft_id: null,
                facility_id: null,
                query_type: 1,
                index: 1,
                size: 10,
            };
            this.station1Data = [];
        },

        // 工站2查询方法
        handleStation2Query() {
            this.station2Query.index = 1;
            this.loadStation2PDF();
        },

        resetStation2Query() {
            this.station2Query = {
                aircraft_id: null,
                facility_id: null,
                query_type: 1,
                index: 1,
                size: 10,
            };
            this.station2Data = [];
        },

        // 工站1 PDF加载方法
        loadStation1PDF() {
            this.station1Loading = true;
            this.station1Data = [];

            const queryParams = {
                facility_id: this.station1Query.facility_id || null,
                aircraft_id: this.station1Query.aircraft_id || null,
                query_type: this.station1Query.query_type !== undefined ? this.station1Query.query_type : 1,
                station: 1
            };

            Object.keys(queryParams).forEach(key => {
                if (queryParams[key] === null || queryParams[key] === undefined) {
                    delete queryParams[key];
                }
            });

            console.log('工站1查询参数:', queryParams);

            getStation(queryParams).then((res) => {
                console.log('工站1 API响应:', res);

                if (res.data instanceof ArrayBuffer) {
                    const uint8Array = new Uint8Array(res.data);
                    this.station1Data = [{
                        pdf_buffer: uint8Array,
                        pdf_name: '工站1查询结果.pdf',
                        facility_name: '工站1查询结果',
                        sop_id: 1
                    }];
                } else if (typeof res.data === 'string' && res.data.startsWith('%PDF')) {
                    this.station1Data = [{
                        pdf_raw_content: res.data,
                        pdf_name: '工站1查询结果.pdf',
                        facility_name: '工站1查询结果',
                        sop_id: 1
                    }];
                } else if (res.data && res.data.data) {
                    this.station1Data = res.data.data;
                } else {
                    this.station1Data = [];
                }

                this.station1Loading = false;
                this.loadAllStation1PDFs();
            }).catch(error => {
                this.station1Loading = false;
                console.error('工站1获取数据错误:', error);
            });
        },

        // 工站2 PDF加载方法
        loadStation2PDF() {
            this.station2Loading = true;
            this.station2Data = [];

            const queryParams = {
                facility_id: this.station2Query.facility_id || null,
                aircraft_id: this.station2Query.aircraft_id || null,
                query_type: this.station2Query.query_type !== undefined ? this.station2Query.query_type : 1,
                station: 2
            };

            Object.keys(queryParams).forEach(key => {
                if (queryParams[key] === null || queryParams[key] === undefined) {
                    delete queryParams[key];
                }
            });

            console.log('工站2查询参数:', queryParams);

            getStation(queryParams).then((res) => {
                console.log('工站2 API响应:', res);

                if (res.data instanceof ArrayBuffer) {
                    const uint8Array = new Uint8Array(res.data);
                    this.station2Data = [{
                        pdf_buffer: uint8Array,
                        pdf_name: '工站2查询结果.pdf',
                        facility_name: '工站2查询结果',
                        sop_id: 1
                    }];
                } else if (typeof res.data === 'string' && res.data.startsWith('%PDF')) {
                    this.station2Data = [{
                        pdf_raw_content: res.data,
                        pdf_name: '工站2查询结果.pdf',
                        facility_name: '工站2查询结果',
                        sop_id: 1
                    }];
                } else if (res.data && res.data.data) {
                    this.station2Data = res.data.data;
                } else {
                    this.station2Data = [];
                }

                this.station2Loading = false;
                this.loadAllStation2PDFs();
            }).catch(error => {
                this.station2Loading = false;
                console.error('工站2获取数据错误:', error);
            });
        },

        // 加载所有工站1 PDF文件
        loadAllStation1PDFs() {
            this.station1Data.forEach((item, index) => {
                this.$set(item, 'loading', true);
                this.$set(item, 'pdfSrc', null);
                this.$set(item, 'station1PdfDoc', null);
                this.$set(item, 'currentPage', 1);
                this.$set(item, 'totalPages', 1);

                this.loadSingleStationPDF(item, index, 'station1');
            });
        },

        // 加载所有工站2 PDF文件
        loadAllStation2PDFs() {
            this.station2Data.forEach((item, index) => {
                this.$set(item, 'loading', true);
                this.$set(item, 'pdfSrc', null);
                this.$set(item, 'station2PdfDoc', null);
                this.$set(item, 'currentPage', 1);
                this.$set(item, 'totalPages', 1);

                this.loadSingleStationPDF(item, index, 'station2');
            });
        },

        // 加载单个工站PDF文件
        loadSingleStationPDF(item, index, stationType) {
            if (item.pdf_buffer && item.pdf_buffer instanceof Uint8Array) {
                console.log(`${stationType} 使用PDF buffer数据`);
                this.renderStationPDFFromBuffer(item.pdf_buffer, item, index, stationType);
            } else if (item.pdf_raw_content && typeof item.pdf_raw_content === 'string') {
                console.log(`${stationType} 使用PDF原始内容数据`);
                const uint8Array = this.convertPDFStringToUint8ArrayImproved(item.pdf_raw_content);
                if (uint8Array) {
                    this.renderStationPDFFromBuffer(uint8Array, item, index, stationType);
                } else {
                    this.$set(item, 'loading', false);
                    console.error(`${stationType} PDF数据转换失败`);
                }
            } else {
                this.$set(item, 'loading', false);
                console.log(`${stationType} 没有PDF数据`);
            }
        },

        // 改进的PDF字符串转换方法
        convertPDFStringToUint8ArrayImproved(pdfString) {
            try {
                const uint8Array = new Uint8Array(pdfString.length);
                for (let i = 0; i < pdfString.length; i++) {
                    const charCode = pdfString.charCodeAt(i);
                    uint8Array[i] = charCode & 0xFF;
                }

                const header = Array.from(uint8Array.slice(0, 4)).map(b => String.fromCharCode(b)).join('');
                if (header === '%PDF') {
                    return uint8Array;
                }
                return null;
            } catch (error) {
                console.error('PDF字符串转换失败:', error);
                return null;
            }
        },

        // 渲染工站PDF从Buffer
        async renderStationPDFFromBuffer(buffer, item, index, stationType) {
            try {
                const loadingTask = pdfjsLib.getDocument({
                    data: buffer,
                    verbosity: 0,
                    cMapUrl: '/static/pdfjs/cmaps/',
                    cMapPacked: true,
                    standardFontDataUrl: '/static/pdfjs/standard_fonts/'
                });

                const pdfDoc = await loadingTask.promise;

                this.$set(item, `${stationType}PdfDoc`, pdfDoc);
                this.$set(item, 'totalPages', pdfDoc.numPages);
                this.$set(item, 'currentPage', 1);
                this.$set(item, 'pdfSrc', 'loaded');
                this.$set(item, 'loading', false);

                // 等待DOM更新后渲染第一页
                this.$nextTick(() => {
                    setTimeout(() => {
                        const canvasRefName = `${stationType}Canvas${index}`;
                        this.waitForCanvasAndRender(pdfDoc, 1, 1.3, canvasRefName);
                    }, 100);
                });

                console.log(`${stationType} PDF加载成功，共 ${pdfDoc.numPages} 页`);
            } catch (error) {
                this.$set(item, 'loading', false);
                console.error(`${stationType} PDF渲染失败:`, error);
            }
        },

        // 等待Canvas准备好并渲染
        waitForCanvasAndRender(pdfDoc, pageNum, scale, canvasRefName, maxRetries = 10) {
            const canvas = this.$refs[canvasRefName];
            if (canvas && canvas[0]) {
                console.log('✅ Canvas找到，开始渲染PDF');
                this.renderPDFPage(pdfDoc, pageNum, canvas[0], scale);
                return;
            }

            if (maxRetries <= 0) {
                console.error('❌ Canvas等待超时，无法渲染PDF');
                return;
            }

            console.log(`⏳ Canvas未准备好，100ms后重试，剩余重试次数: ${maxRetries}`);
            setTimeout(() => {
                this.waitForCanvasAndRender(pdfDoc, pageNum, scale, canvasRefName, maxRetries - 1);
            }, 100);
        },

        // 简化的PDF页面渲染
        async renderPDFPage(pdfDoc, pageNum, canvas, scale = 1) {
            try {
                const page = await pdfDoc.getPage(pageNum);
                const viewport = page.getViewport({ scale });

                if (!canvas) {
                    console.error('Canvas未找到');
                    return;
                }

                const context = canvas.getContext('2d');
                canvas.height = viewport.height;
                canvas.width = viewport.width;

                // 清除Canvas
                context.fillStyle = 'white';
                context.fillRect(0, 0, canvas.width, canvas.height);

                const renderContext = {
                    canvasContext: context,
                    viewport: viewport,
                    background: 'white',
                    intent: 'display'
                };

                const renderTask = page.render(renderContext);
                await renderTask.promise;

            } catch (error) {
                console.error('渲染PDF页面失败:', error);
            }
        },

        // 工站1翻页方法
        prevStation1Page(item) {
            if (item.currentPage > 1) {
                this.$set(item, 'currentPage', item.currentPage - 1);
                this.$nextTick(() => {
                    const index = this.station1Data.indexOf(item);
                    const canvasRefName = `station1Canvas${index}`;
                    this.waitForCanvasAndRender(item.station1PdfDoc, item.currentPage, 1.3, canvasRefName);
                });
            }
        },

        nextStation1Page(item) {
            if (item.currentPage < item.totalPages) {
                this.$set(item, 'currentPage', item.currentPage + 1);
                this.$nextTick(() => {
                    const index = this.station1Data.indexOf(item);
                    const canvasRefName = `station1Canvas${index}`;
                    this.waitForCanvasAndRender(item.station1PdfDoc, item.currentPage, 1.3, canvasRefName);
                });
            }
        },

        // 工站2翻页方法
        prevStation2Page(item) {
            if (item.currentPage > 1) {
                this.$set(item, 'currentPage', item.currentPage - 1);
                this.$nextTick(() => {
                    const index = this.station2Data.indexOf(item);
                    const canvasRefName = `station2Canvas${index}`;
                    this.waitForCanvasAndRender(item.station2PdfDoc, item.currentPage, 1.3, canvasRefName);
                });
            }
        },

        nextStation2Page(item) {
            if (item.currentPage < item.totalPages) {
                this.$set(item, 'currentPage', item.currentPage + 1);
                this.$nextTick(() => {
                    const index = this.station2Data.indexOf(item);
                    const canvasRefName = `station2Canvas${index}`;
                    this.waitForCanvasAndRender(item.station2PdfDoc, item.currentPage, 1.3, canvasRefName);
                });
            }
        },

        // 工站1全屏PDF查看相关方法
        openStation1Fullscreen(item) {
            this.station1FullscreenVisible = true;
            this.station1FullscreenPdfDoc = item.station1PdfDoc;
            this.station1FullscreenCurrentPage = item.currentPage || 1;
            this.station1FullscreenTotalPages = item.totalPages || 1;
            this.station1FullscreenScale = 1;

            document.body.style.overflow = 'hidden';

            this.$nextTick(() => {
                this.renderPDFPage(this.station1FullscreenPdfDoc, this.station1FullscreenCurrentPage, this.$refs.station1FullscreenCanvas, this.station1FullscreenScale);
            });
        },

        closeStation1Fullscreen() {
            this.station1FullscreenVisible = false;
            document.body.style.overflow = '';
        },

        prevStation1FullscreenPage() {
            if (this.station1FullscreenCurrentPage > 1) {
                this.station1FullscreenCurrentPage--;
                this.renderPDFPage(this.station1FullscreenPdfDoc, this.station1FullscreenCurrentPage, this.$refs.station1FullscreenCanvas, this.station1FullscreenScale);
            }
        },

        nextStation1FullscreenPage() {
            if (this.station1FullscreenCurrentPage < this.station1FullscreenTotalPages) {
                this.station1FullscreenCurrentPage++;
                this.renderPDFPage(this.station1FullscreenPdfDoc, this.station1FullscreenCurrentPage, this.$refs.station1FullscreenCanvas, this.station1FullscreenScale);
            }
        },

        station1FullscreenZoomIn() {
            if (this.station1FullscreenScale < 3) {
                this.station1FullscreenScale += 0.25;
                this.renderPDFPage(this.station1FullscreenPdfDoc, this.station1FullscreenCurrentPage, this.$refs.station1FullscreenCanvas, this.station1FullscreenScale);
            }
        },

        station1FullscreenZoomOut() {
            if (this.station1FullscreenScale > 0.5) {
                this.station1FullscreenScale -= 0.25;
                this.renderPDFPage(this.station1FullscreenPdfDoc, this.station1FullscreenCurrentPage, this.$refs.station1FullscreenCanvas, this.station1FullscreenScale);
            }
        },

        // 工站2全屏PDF查看相关方法
        openStation2Fullscreen(item) {
            this.station2FullscreenVisible = true;
            this.station2FullscreenPdfDoc = item.station2PdfDoc;
            this.station2FullscreenCurrentPage = item.currentPage || 1;
            this.station2FullscreenTotalPages = item.totalPages || 1;
            this.station2FullscreenScale = 1;

            document.body.style.overflow = 'hidden';

            this.$nextTick(() => {
                this.renderPDFPage(this.station2FullscreenPdfDoc, this.station2FullscreenCurrentPage, this.$refs.station2FullscreenCanvas, this.station2FullscreenScale);
            });
        },

        closeStation2Fullscreen() {
            this.station2FullscreenVisible = false;
            document.body.style.overflow = '';
        },

        prevStation2FullscreenPage() {
            if (this.station2FullscreenCurrentPage > 1) {
                this.station2FullscreenCurrentPage--;
                this.renderPDFPage(this.station2FullscreenPdfDoc, this.station2FullscreenCurrentPage, this.$refs.station2FullscreenCanvas, this.station2FullscreenScale);
            }
        },

        nextStation2FullscreenPage() {
            if (this.station2FullscreenCurrentPage < this.station2FullscreenTotalPages) {
                this.station2FullscreenCurrentPage++;
                this.renderPDFPage(this.station2FullscreenPdfDoc, this.station2FullscreenCurrentPage, this.$refs.station2FullscreenCanvas, this.station2FullscreenScale);
            }
        },

        station2FullscreenZoomIn() {
            if (this.station2FullscreenScale < 3) {
                this.station2FullscreenScale += 0.25;
                this.renderPDFPage(this.station2FullscreenPdfDoc, this.station2FullscreenCurrentPage, this.$refs.station2FullscreenCanvas, this.station2FullscreenScale);
            }
        },

        station2FullscreenZoomOut() {
            if (this.station2FullscreenScale > 0.5) {
                this.station2FullscreenScale -= 0.25;
                this.renderPDFPage(this.station2FullscreenPdfDoc, this.station2FullscreenCurrentPage, this.$refs.station2FullscreenCanvas, this.station2FullscreenScale);
            }
        },

        // 处理键盘事件
        handleKeyDown(event) {
            if (event.key === 'Escape') {
                if (this.station1FullscreenVisible) {
                    this.closeStation1Fullscreen();
                } else if (this.station2FullscreenVisible) {
                    this.closeStation2Fullscreen();
                }
            }
        }
    },

    // 组件销毁时清理PDF资源
    beforeDestroy() {
        // 移除键盘事件监听
        document.removeEventListener('keydown', this.handleKeyDown);

        // 清理PDF文档对象
        if (this.station1FullscreenPdfDoc) {
            this.station1FullscreenPdfDoc.destroy();
        }
        if (this.station2FullscreenPdfDoc) {
            this.station2FullscreenPdfDoc.destroy();
        }

        // 清理所有工站中的PDF文档
        if (this.station1Data && Array.isArray(this.station1Data)) {
            this.station1Data.forEach(item => {
                if (item.station1PdfDoc) {
                    item.station1PdfDoc.destroy();
                }
            });
        }
        if (this.station2Data && Array.isArray(this.station2Data)) {
            this.station2Data.forEach(item => {
                if (item.station2PdfDoc) {
                    item.station2PdfDoc.destroy();
                }
            });
        }
    }
};
</script>

<style lang="scss" scoped>
.message {
    width: 198%;
    background: #f8f8f9;
    display: flex;
    overflow-x: scroll;
}

.activeClass {
    color: red;
}

::v-deep .el-table .el-table__body-wrapper::-webkit-scrollbar {
    height: 15px !important;
}

.dialog-footer {
    text-align: right;
}

// 双工站左右分屏布局样式
.dual-station-layout {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
    height: calc(100vh - 200px);
    min-height: 600px;
}

.station-panel {
    border: 2px solid #e4e7ed;
    border-radius: 8px;
    padding: 15px;
    background: #fafbfc;
    overflow-y: auto;
    
    &.station-1 {
        border-color: #409EFF;
        
        .station-header h3 {
            color: #409EFF;
        }
    }
    
    &.station-2 {
        border-color: #67C23A;
        
        .station-header h3 {
            color: #67C23A;
        }
    }
    
    .station-header {
        text-align: center;
        margin-bottom: 15px;
        padding-bottom: 10px;
        border-bottom: 2px solid #e4e7ed;
        
        h3 {
            margin: 0;
            font-size: 18px;
            font-weight: bold;
        }
    }
    
    .el-form {
        margin-bottom: 15px;
        padding: 10px;
        background: white;
        border-radius: 6px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }
}

.station-content {
    flex: 1;
    overflow-y: auto;
}

.pdf-card {
    width: 100%;
    margin-bottom: 15px;
    
    .pdf-card-header {
        display: flex;
        justify-content: center;
        align-items: center;
        
        .pdf-title {
            font-size: 16px;
            font-weight: bold;
            color: #303133;
        }
    }
    
    .pdf-content {
        .pdf-viewer {
            width: 100%;
            border-radius: 6px;
            overflow: hidden;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
            
            .pdf-canvas {
                width: 100%;
                max-width: 100%;
                height: auto;
                cursor: pointer;
                transition: transform 0.2s ease;
                
                &:hover {
                    transform: scale(1.02);
                }
            }
            
            .pdf-controls {
                display: flex;
                justify-content: center;
                align-items: center;
                gap: 8px;
                padding: 10px;
                background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
                border-top: 1px solid #e4e7ed;
                
                .page-info {
                    font-size: 12px;
                    color: #606266;
                    margin: 0 8px;
                    font-weight: 600;
                    background: white;
                    padding: 2px 6px;
                    border-radius: 8px;
                    min-width: 60px;
                    text-align: center;
                }
                
                :deep(.el-button) {
                    font-size: 12px;
                    padding: 5px 8px;
                    border-radius: 12px;
                }
            }
        }
        
        .pdf-loading,
        .pdf-error {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 150px;
            color: #909399;
            border: 2px dashed #e4e7ed;
            border-radius: 4px;
            
            i {
                font-size: 20px;
                margin-bottom: 6px;
            }
            
            span {
                font-size: 12px;
            }
        }
        
        .pdf-loading {
            color: #409EFF;
            border-color: #c6e2ff;
            
            i {
                animation: rotating 2s linear infinite;
            }
        }
        
        .pdf-error {
            color: #F56C6C;
            border-color: #fbc4c4;
        }
    }
}

.empty-state {
    text-align: center;
    margin-top: 30px;
    color: #909399;
}

// 全屏PDF样式
.fullscreen-pdf-container {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    background: rgba(0, 0, 0, 0.9);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 9999;

    .fullscreen-content {
        width: 90%;
        height: 90%;
        display: flex;
        flex-direction: column;
        background: white;
        border-radius: 8px;
        overflow: hidden;
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);

        .fullscreen-pdf-canvas {
            flex: 1;
            width: 100%;
            height: auto;
            max-height: calc(100% - 70px);
            object-fit: contain;
        }

        .fullscreen-controls {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 20px;
            padding: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);

            .page-info {
                font-size: 18px;
                color: white;
                margin: 0 20px;
                font-weight: 600;
                background: rgba(255, 255, 255, 0.2);
                padding: 6px 15px;
                border-radius: 15px;
                backdrop-filter: blur(10px);
            }

            .zoom-info {
                font-size: 16px;
                color: white;
                margin: 0 15px;
                font-weight: 600;
                background: rgba(255, 255, 255, 0.2);
                padding: 4px 12px;
                border-radius: 12px;
                backdrop-filter: blur(10px);
            }

            :deep(.el-button) {
                border-radius: 20px;
                font-weight: 600;
                backdrop-filter: blur(10px);

                &.el-button--primary {
                    background: rgba(64, 158, 255, 0.8);
                    border-color: rgba(64, 158, 255, 0.8);
                }

                &.el-button--danger {
                    background: rgba(245, 108, 108, 0.8);
                    border-color: rgba(245, 108, 108, 0.8);
                }

                &:not(.el-button--primary):not(.el-button--danger) {
                    background: rgba(255, 255, 255, 0.9);
                    color: #333;
                    border-color: rgba(255, 255, 255, 0.9);
                }
            }
        }
    }
}

@keyframes rotating {
    from {
        transform: rotate(0deg);
    }
    to {
        transform: rotate(360deg);
    }
}
</style> 